package cn.bonoon.kernel.util;

import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class XmlParser {
	private static final Logger log = LoggerFactory.getLogger(XmlParser.class);

	private final static String ATTR_VALUE = "value";

	protected Element getRootElement(String filename) {
		Document document = load(filename);
		if (null != document)
			return document.getRootElement();

		return null;
	}

	/**
	 * load 载入一个xml文档
	 * 
	 * @return 成功返回Document对象，失败返回null
	 * @param uri
	 *            文件路径
	 */
	protected Document load(String filename) {
		Document document = null;
		try {
			SAXReader saxReader = new SAXReader();
			InputStream is = getClass().getResourceAsStream(filename);
			document = saxReader.read(is);
		} catch (Exception ex) {
			ex.printStackTrace();
			log.error("cannt read file{}", filename);
		}
		return document;
	}

	protected static String getValue(Element element) {
		return element.attributeValue(ATTR_VALUE);
	}

	protected static String getBoth(Element element, String name) {
		String str = element.attributeValue(name);
		if (StringHelper.isEmpty(str)) {
			Element ele = element.element(name);
			if (null != ele) {
				str = getValue(ele);
				if (StringHelper.isEmpty(str)) {
					str = ele.getTextTrim();
				}
			}
		}
		return str;
	}

	protected static int getInteger(Element element, String name) {
		return StringHelper.toint(getBoth(element, name));
	}

	protected static boolean getBoolean(Element element, String name) {
		String ad = element.attributeValue(name);
		return "true".equalsIgnoreCase(ad);
	}

	protected static boolean getBooleanTrue(Element element, String name) {
		String ad = element.attributeValue(name);
		if (StringHelper.isNotEmpty(ad))
			return "true".equalsIgnoreCase(ad);
		return true;
	}

	protected static String getText(Element element, String name) {
		Element nameElement = element.element(name);
		return null != nameElement ? nameElement.getTextTrim() : null;
	}

	protected static String getValue(Element element, String name) {
		return element.attributeValue(name);
	}

	protected static String getValueOrText(Element element) {
		String vt = element.attributeValue(ATTR_VALUE);
		if (StringHelper.isEmpty(vt)) {
			vt = element.getTextTrim();
		}
		return vt;
	}
}
